package com.scalar.forecast.projectSetup.actionCommands;

import com.scalar.forecast.actionCommands.ActionCommand;
import com.scalar.forecast.projectSetup.forms.ProjectSetupForm;
import com.scalar.forecast.projectSetup.dao.ProjectSetupDAO;
import com.scalar.forecast.projectSetup.dao.UserDefinedFieldsDAO;
import com.scalar.forecast.projectSetup.ProjectSetup;
import com.scalar.forecast.commons.SessionKeys;
import com.scalar.forecast.forecastEntry.dao.ForecastEntrySearchDAO;
import com.scalar.forecast.forecastSetup.dao.ForecastSetupDAO;
import com.scalar.forecast.salesPersonSetup.dao.SalesPersonSetupDAO;

import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.CustomerRelationshipDAO;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;


/**
 * Process the request to keep the Project Setup details in scope and directs to confirm page
 *
 * Created by Veeru.
 * Date: Feb 8, 2005
 * Time: 12:38:25 PM
 */

public class ProjectSetupSaveCommand extends ActionCommand {

    public ActionForward execute( ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response ) {

        ActionForward actionForward = mapping.findForward( "confirmProjectSetup" );
        ProjectSetupForm projectSetupForm = ( ProjectSetupForm )form;
        ProjectSetup projectSetup = projectSetupForm.getProjectSetup();

        HashMap errors = new HashMap ();
        request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
        request.setAttribute( "purpose","save" );

        try {
            String salesPerson = ProjectSetupDAO.getSalesPersonForProject( null, projectSetup.getProjectName(), projectSetup.getProjectID() );
            if ( salesPerson != null && salesPerson.trim().length() > 0 ) {
                errors.put( "Project with this name is already assigned to Sales Person : "+salesPerson, null );
                request.setAttribute( "customers", ForecastEntrySearchDAO.getAllCustomers( null ) );
                request.setAttribute( "odmsList", CustomerRelationshipDAO.getAllOdmsForCustomer( projectSetup.getCustomerID()+"" ) );
                request.setAttribute( "endUserList", CustomerRelationshipDAO.getAllEndCustomerList( projectSetup.getCustomerID()+"") );
                request.setAttribute( "salesPersons", SalesPersonSetupDAO.getSalesPersonList() );
                ArrayList newUserDefinedfields = UserDefinedFieldsDAO.loadNewUserDefinedFieldValues( null, projectSetup.getProjectID(), projectSetup.getUserDefinedFeilds() );
                projectSetup.setUserDefinedFeilds( newUserDefinedfields );
                ProjectSetupDAO.convertPartNumberArraysToList( null, projectSetup );
                request.setAttribute( "availableChipsList" , projectSetup.getAvailableChipsList() );
                request.setAttribute( "availableBoardsList" , projectSetup.getAvailableBoardsList() );
                request.setAttribute( "availableKitsList" , projectSetup.getAvailableKitsList() );
                actionForward = mapping.findForward( "projectSetup" );
            } else {
                ProjectSetupDAO.convertPartNumberArraysToList( null, projectSetup );
                ArrayList selectedParts = projectSetup.getSelectedParts();

                boolean found = true;
                String productsNotFound  = null;
                String forecastedProduct = null;
                ArrayList forecastedProducts = ForecastSetupDAO.loadFoecastedPoducts( null, projectSetup.getProjectID() );

                for (int i = 0; i < forecastedProducts.size(); i++) {
                    forecastedProduct = (String) forecastedProducts.get(i);
                    if ( !selectedParts.contains( forecastedProduct ) ) {
                        if ( productsNotFound == null ){
                            productsNotFound = ProjectSetupDAO.getPartNumber( null, Integer.parseInt( forecastedProduct ) );
                        }else {
                            productsNotFound += ", "+ProjectSetupDAO.getPartNumber( null, Integer.parseInt( forecastedProduct ) );
                        }
                        found = false;
                    }
                }
                if( !found ){
                    if ( productsNotFound.indexOf(",") > 0 ){
                        errors.put("For the following products "+productsNotFound+" Forecast is generated so cannot be deselected", null );
                    } else {
                        errors.put("For the product "+productsNotFound+" Forecast is generated so cannot be deselected", null );
                    }
                    request.setAttribute( "customers", ForecastEntrySearchDAO.getAllCustomers( null ) );
                    request.setAttribute( "odmsList", CustomerRelationshipDAO.getAllOdmsForCustomer( projectSetup.getCustomerID()+"" ) );
                    request.setAttribute( "endUserList", CustomerRelationshipDAO.getAllEndCustomerList( projectSetup.getCustomerID()+"" ) );
                    request.setAttribute( "salesPersons", SalesPersonSetupDAO.getSalesPersonList() );
                    ArrayList newUserDefinedfields = UserDefinedFieldsDAO.loadNewUserDefinedFieldValues( null, projectSetup.getProjectID(), projectSetup.getUserDefinedFeilds() );
                    projectSetup.setUserDefinedFeilds( newUserDefinedfields );
                    ProjectSetupDAO.convertPartNumberArraysToList( null, projectSetup );
                    request.setAttribute( "availableChipsList" , projectSetup.getAvailableChipsList() );
                    request.setAttribute( "availableBoardsList" , projectSetup.getAvailableBoardsList() );
                    request.setAttribute( "availableKitsList" , projectSetup.getAvailableKitsList() );
                    actionForward = mapping.findForward( "projectSetup" );
                } else {
                    projectSetup.setCustomerName( CustomerDAO.getCustomerName( null, projectSetup.getCustomerID() ) );
                    projectSetup.setOdmName( CustomerDAO.getCustomerName( null, projectSetup.getOdmID() ) );
                    projectSetup.setEndUserName( CustomerDAO.getCustomerName( null, projectSetup.getEndUserId() ) );
                    projectSetup.setSalesPerson( SalesPersonSetupDAO.getSalesPersonName( null, projectSetup.getSalesPersonID() ) );
                    if ( projectSetup.getProjectID() > 0 && ProjectSetupDAO.isProjectHasForecastEntry ( null, projectSetup.getProjectID() ) )
                    {
                        if ( ProjectSetupDAO.isForeCastToBeModified( null, projectSetup ))
                        {
                            request.setAttribute ( "isForecastToBeModified", "true" );
                        }
                    }
                }
            }

        } catch ( Exception e){
            e.printStackTrace();
            errors.put( "Error while saving the project setup details", null );
            actionForward = mapping.findForward( "projectSearch" );
        }
        request.setAttribute( "selectedChipsList" , projectSetup.getSelectedChipsList() );
        request.setAttribute( "selectedBoardsList" , projectSetup.getSelectedBoardsList() );
        request.setAttribute( "selectedKitsList" ,  projectSetup.getSelectedKitsList() );
        return actionForward;
    }
}
